import datetime
from tkinter import *
from typing import Dict
from tkinter.ttk import *
import sys


class Log:
    def __init__(self, tk):
        self.tk: Text = tk

    def write(self, info):
        self.tk.insert(1.0, info)
        return 0

    def flush(self):
        pass

    def close(self):
        pass


class WinGUI(Tk):
    widget_dic: Dict[str, Widget] = {}

    def __init__(self):
        super().__init__()
        self.__win()
        self.widget_dic["tk_text_log"] = self.__tk_text_log(self)
        self.widget_dic["tk_button_lhu6z2w5"] = self.__tk_button_lhu6z2w5(self)
        self.widget_dic["tk_button_lhu6zau4"] = self.__tk_button_lhu6zau4(self)

    def __win(self):
        self.title("测试打印日志信息")
        # 设置窗口大小、居中
        width = 386
        height = 251
        screenwidth = self.winfo_screenwidth()
        screenheight = self.winfo_screenheight()
        geometry = '%dx%d+%d+%d' % (width, height,
                                    (screenwidth - width) / 2, (screenheight - height) / 2)
        self.geometry(geometry)
        self.resizable(width=False, height=False)

        # 自动隐藏滚动条
    def scrollbar_autohide(self, bar, widget):
        self.__scrollbar_hide(bar, widget)
        widget.bind("<Enter>", lambda e: self.__scrollbar_show(bar, widget))
        bar.bind("<Enter>", lambda e: self.__scrollbar_show(bar, widget))
        widget.bind("<Leave>", lambda e: self.__scrollbar_hide(bar, widget))
        bar.bind("<Leave>", lambda e: self.__scrollbar_hide(bar, widget))

    def __scrollbar_show(self, bar, widget):
        bar.lift(widget)

    def __scrollbar_hide(self, bar, widget):
        bar.lower(widget)

    def __tk_text_log(self, parent):
        text = Text(parent)
        text.place(x=10, y=90, width=366, height=149)

        return text

    def __tk_button_lhu6z2w5(self, parent):
        def test_print():
            i = datetime.datetime.now()  # 获取当前时间
            print('今天是{}月{}日{}点{}分{}秒'.format(
                i.month, i.day, i.hour, i.minute, i.second))

        btn = Button(parent, text="打印", takefocus=False, command=test_print)
        btn.place(x=30, y=30, width=50, height=30)
        return btn

    def __tk_button_lhu6zau4(self, parent):
        def clean():
            self.widget_dic['tk_text_log'].delete(1.0, END)
        btn = Button(parent, text="清空", takefocus=False, command=clean)
        btn.place(x=290, y=30, width=50, height=30)
        return btn


class Win(WinGUI):
    def __init__(self):
        super().__init__()
        self.__event_bind()

    def __event_bind(self):
        pass


if __name__ == "__main__":
    win = Win()
    sys.stdout = Log(tk=win.widget_dic['tk_text_log'])
    win.mainloop()
